<?php

/***  Documentation

    Greqo Analytics API Test
    
    Revision: $Rev: 114 $
    Last Update: $Date: 2009-10-01 04:39:01 +0000 (Thu, 01 Oct 2009) $
    Author: Tom at klenwell@gmail.com
  
NOTES

______________________________________________________________________________*/

$dn1 = dirname;
$ds = DIRECTORY_SEPARATOR;
$libdir = $dn1($dn1($dn1(__FILE__))) . $ds . 'lib' . $ds;
$grqdir = $dn1($libdir) . $ds . 'greqo' . $ds;
require_once($libdir . "simpletest{$ds}unit_tester.php");
require_once($grqdir . "analytics.class.php");

class GaApiTestCase extends UnitTestCase {
    
    var $debug = 0;
    var $is_set_up_once = 0;
    var $ga_api_xml = '';
    
    function setUp() 
    {
        $this->setUpOnce();  
    }
    
    function tearDown() 
    {
    }
    
    function setUpOnce()
    {
        if ( $this->is_set_up_once ) return;      
        
        // set up
        $utime = microtime();
        $this->start_timer = substr($utime,0,9) + substr($utime,-10);
        $this->is_set_up_once = 1;
        
        $this->Analytics = new GreqoAnalytics($start_session=0);
        
        $this->ga_api_xml = <<<XXML
<?xml version='1.0' encoding='UTF-8'?>
<feed xmlns='http://www.w3.org/2005/Atom' xmlns:dxp='http://schemas.google.com/analytics/2009' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/'>
	<id>http://www.google.com/analytics/feeds/data?ids=ga:1264425&amp;dimensions=ga:date&amp;metrics=ga:pageviews,ga:visitors,ga:visits&amp;start-date=2009-09-26&amp;end-date=2009-09-27</id>
	<updated>2009-09-27T13:55:49.053-07:00</updated>
	<title type='text'>Google Analytics Data for Profile 1264425</title>
	<link rel='self' type='application/atom+xml' href='http://www.google.com/analytics/feeds/data?max-results=5&amp;sort=ga%3Avisitors&amp;end-date=2009-09-27&amp;start-date=2009-09-26&amp;metrics=ga%3Avisitors%2Cga%3Avisits%2Cga%3Apageviews&amp;ids=ga%3A1264425&amp;dimensions=ga%3Adate'/>
	<author>
		<name>Google Analytics</name>
	</author>
	<generator version='1.0'>Google Analytics</generator>
	<openSearch:totalResults>2</openSearch:totalResults>
	<openSearch:startIndex>1</openSearch:startIndex>
	<openSearch:itemsPerPage>5</openSearch:itemsPerPage>
	<dxp:aggregates>
		<dxp:metric confidenceInterval='0.0' name='ga:visitors' type='integer' value='26'/>
		<dxp:metric confidenceInterval='0.0' name='ga:visits' type='integer' value='29'/>
		<dxp:metric confidenceInterval='0.0' name='ga:pageviews' type='integer' value='31'/>
	</dxp:aggregates>
	<dxp:dataSource>
		<dxp:property name='ga:profileId' value='1264425'/>
		<dxp:property name='ga:webPropertyId' value='UA-75217-12'/>
		<dxp:property name='ga:accountName' value='Klenwell'/>
		<dxp:tableId>ga:1264425</dxp:tableId>
		<dxp:tableName>Phosphorus and Lime (blog)</dxp:tableName>
	</dxp:dataSource>
	<dxp:endDate>2009-09-27</dxp:endDate>
	<dxp:startDate>2009-09-26</dxp:startDate>
	<entry>
		<id>http://www.google.com/analytics/feeds/data?ids=ga:1264425&amp;ga:date=20090926&amp;start-date=2009-09-26&amp;end-date=2009-09-27</id>
		<updated>2009-09-26T17:00:00.001-07:00</updated>
		<title type='text'>ga:date=20090926</title>
		<link rel='alternate' type='text/html' href='http://www.google.com/analytics'/>
		<dxp:dimension name='ga:date' value='20090926'/>
		<dxp:metric confidenceInterval='0.0' name='ga:visitors' type='integer' value='12'/>
		<dxp:metric confidenceInterval='0.0' name='ga:visits' type='integer' value='13'/>
		<dxp:metric confidenceInterval='0.0' name='ga:pageviews' type='integer' value='13'/>
	</entry>
	<entry>
		<id>http://www.google.com/analytics/feeds/data?ids=ga:1264425&amp;ga:date=20090927&amp;start-date=2009-09-26&amp;end-date=2009-09-27</id>
		<updated>2009-09-26T17:00:00.001-07:00</updated>
		<title type='text'>ga:date=20090927</title>
		<link rel='alternate' type='text/html' href='http://www.google.com/analytics'/>
		<dxp:dimension name='ga:date' value='20090927'/>
		<dxp:metric confidenceInterval='0.0' name='ga:visitors' type='integer' value='14'/>
		<dxp:metric confidenceInterval='0.0' name='ga:visits' type='integer' value='16'/>
		<dxp:metric confidenceInterval='0.0' name='ga:pageviews' type='integer' value='18'/>
	</entry>
</feed>
XXML;

    }
    
    

    /* TEST METHODS */  
    function testParseApiXmlAggregates()
    {
        $XmlDoc = $this->Analytics->parse_xml($this->ga_api_xml);

        $report_title = $XmlDoc->title[0]->tagData;

        $AggregateDict = array();
        foreach ( $XmlDoc->dxp_aggregates[0]->tagChildren as $Node )
            $AggregateDict[$Node->tagAttrs['name']] = $Node->tagAttrs['value'];

        $this->assertEqual( $report_title, 'Google Analytics Data for Profile 1264425' );
        $this->assertEqual( $AggregateDict['ga:visitors'], 26 );
    }
    
    function testParseApiXmlEntries()
    {
        $XmlDoc = $this->Analytics->parse_xml($this->ga_api_xml);
        
        $EntryDict = array();
        foreach ( $XmlDoc->entry as $EntryNode )
        {
            $DimDict = array();
            $MetricDict = array();
            
            foreach ( $EntryNode->dxp_dimension as $Dim )
                $DimDict[$Dim->tagAttrs['name']] = $Dim->tagAttrs['value'];
            
            foreach ( $EntryNode->dxp_metric as $Metric )
                $MetricDict[$Metric->tagAttrs['name']] = $Metric->tagAttrs['value'];

            $EntryDict[$DimDict['ga:date']] = array_merge($DimDict, $MetricDict);
        }
        
        $this->assertEqual( $EntryDict['20090926']['ga:visitors'], 12 );
        $this->assertEqual( $EntryDict['20090926']['ga:visits'], 13 );
    }
    
    function testParseApiXmlDatasource()
    {
        $XmlDoc = $this->Analytics->parse_xml($this->ga_api_xml);

        $DatasourceDict = array();
        foreach ( $XmlDoc->dxp_datasource[0]->tagChildren as $Node )
            if ( isset($Node->tagAttrs['name']) )
                $DatasourceDict[$Node->tagAttrs['name']] = $Node->tagAttrs['value'];
            else
                $DatasourceDict[$Node->tagName] = $Node->tagData;
            
        $this->pr($DatasourceDict);
    }



    /* HELPER METHODS */
    function get_script_time()
    {
        $utime = microtime();
        return number_format((substr($utime,0,9) + substr($utime,-10)) - $this->start_timer, 4);
    }

    function kill($html, $message='dying')
    {
        $this->print_d(htmlspecialchars($html), '#600');
        print $html;
        die($message);
    }
    
    function echo_d($message, $color='#ccc')
    {
        $_D = debug_backtrace();
        $f = basename($_D[0]['file']);
        $l = $_D[0]['line'];
        $loc = "{$f}:{$l}";
        $out = "<div style='line-height:1.5em; font-family:monospace; color:$color;'>$message <span style='color:#666;'>[$loc]</span></div>";
        $this->_DBG[] = "$loc -> " . strip_tags($message);
        echo $out;
        return;
    }
    
    function print_d($message, $color='#c33')
    {
        if ( $this->debug ) $this->echo_d($message, $color);
        return;
    }
    
    function print_r($Mixed)
    {
        $return = htmlspecialchars(print_r($Mixed, 1));
        $return = "<pre>$return</pre>";
        return $return;
    }
    
    function pr($Mixed, $header='')
    {
        if ( !empty($header) ) $header = "<b>$header</b>";
        $return = htmlspecialchars(print_r($Mixed, 1));
        $return = "<pre style='border:1px solid #ccc; background:#f3f3f3; padding:4px;'>$header\n\n$return</pre>";
        $this->echo_d($return, '#333');
    }
    
    function dump()
    {
        echo $this->print_r($this);
        return;
    }
}


$Test = &new GaApiTestCase();
$Test->run(new HtmlReporter());

$Test->echo_d('test complete in '.$Test->get_script_time().' s', '#600');
?>
